package com.hemerasolutions.v2trainer.component.detail;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.hemerasolutions.v2trainer.component.BaseComponent;
import com.hemerasolutions.v2trainer.component.interfaces.detail.TrainingDetailsCompInterface;
import com.hemerasolutions.v2trainer.component.interfaces.list.StepListLevelsInterface;
import com.hemerasolutions.v2trainer.dao.interfaces.TrainingDaoInterface;
import com.hemerasolutions.v2trainer.model.step.Step;
import com.hemerasolutions.v2trainer.model.training.Training;
import com.hemerasolutions.v2trainer.model.training.TrainingStep;

@Component("trainingDetails")
@Scope("prototype")
public class TrainingDetailsComp extends BaseComponent implements TrainingDetailsCompInterface {

	private static final long serialVersionUID = 1L;

	private Training training;
	
	private StepListLevelsInterface levelsHandler;

	@Autowired
	private TrainingDaoInterface tsDao;
	
	@Autowired
	private transient ApplicationContext ctx;
	

	@PostConstruct
	@Override
	public void init(){
		super.init();
	}

	@Override
	public void refresh(){

		if(this.training == null){
			this.training = tsDao.list().get(0);
		}
		
		for(TrainingStep ts :this.training.getTrainingSteps()){
			this.collapseAll(ts.getRootStep().getSteps());
		}

		this.levelsHandler = ctx.getBean("stepListLevels",StepListLevelsInterface.class);
		this.levelsHandler.setStepLevels(this.training.getTrainingSteps());
		this.levelsHandler.refresh();

		
	}
	
	

	private void collapseAll(List<Step> steps) {
		for(Step step: steps){
			if(step.getType() > Step.REPETITION_STEP){
				this.collapseAll(step.getSteps());
			}else{
				step.setMark(true);
			}
		}
	}	
		

	@Override
	public Training getTraining() {
		return training;
	}


	@Override
	public void setTraining(Training training) {
		this.training = training;
	}


	@Override
	public StepListLevelsInterface getLevelsHandler() {
		return levelsHandler;
	}


	@Override
	public void setLevelsHandler(StepListLevelsInterface levelsHandler) {
		this.levelsHandler = levelsHandler;
	}




	
}
